<template>
    <el-dialog v-model="visible" title="创建链接" width="670px" @close="handleClose" append-to-body >
        <el-form class="form_link" ref="formRef" :model="form" :rules="rules" label-width="100px">
            <!-- 标题 -->
            <el-form-item label="链接标题" prop="title">
                <el-input v-model="form.title" maxlength="20" show-word-limit placeholder="请输入链接标题"></el-input>
            </el-form-item>
            <!-- 链接地址 -->
            <el-form-item label="链接地址" prop="url">
                <el-input type="text" v-model="form.url" placeholder="请输入链接地址"></el-input>
            </el-form-item>
            <!-- 连接描述 -->
            <el-form-item label="链接描述" prop="desc">
                <el-input type="textarea" v-model="form.desc" :rows="2" maxlength="30" show-word-limit
                    placeholder="请输入链接描述"></el-input>
            </el-form-item>
            <!-- 连接描述 -->
            <el-form-item label="封面" prop="thumbUrl">
                <el-upload ref="avatarUploadRef" class="avatar-uploader" accept=".jpg,.JPG,.jpeg,.JPEG,.png,.PNG"
                    :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="onHttpRequest">
                    <img v-if="form.thumbUrl" :src="form.thumbUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                    <template #tip>
                        <div class="upload-tip">
                            单张图片大小不超过2M，支持png；jpg；jpeg；gif等格式
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="visible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { reactive, defineEmits, nextTick, ref, watch, computed } from "vue";
import { ElForm, ElMessage } from "element-plus";
import type { UploadProps, UploadFile } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import { uploadFile2 } from "@renderer/ajax/api/common";

import { validateHttp } from "../../utils";

const emit = defineEmits(["update:modelValue", "submit"]);

const props = defineProps({
    /** 弹窗显隐藏 */
    modelValue: {
        type: Boolean,
        default: false,
    },
});

const visible = computed({
    get() {
        return props.modelValue;
    },
    set(value) {
        emit("update:modelValue", value);
    },
});

const formRef = ref<InstanceType<typeof ElForm>>();
// 分组ID
const defaultForm = {
    id: 0, // 为0 时表示新增
    type: 3, // 链接
    source: 1, // 默认为1 本地上传
    title: '',
    url: '',
    desc: '',
    fileCode: 0, // 本地上传的文件code (缩略图)
    thumbUrl: '', // 仅回显， 外网的缩略图
    fileInfo: {
        // 仅回显用
        code: "",
        path: "",
        url: "",
        name: "",
    },
}
const form = reactive({...defaultForm});
const rules = reactive({
    title: [
        {
            required: true,
            message: "链接标题不能为空",
            trigger: "blur",
        },
    ],
    url: [
        {
            required: true,
            message: "链接地址不能为空",
            trigger: "blur",
        },
        { validator: validateHttp, trigger: "blur" },
    ],
    desc: [
        {
            required: true,
            message: "链接描述不能为空",
            trigger: "blur",
        },
    ],
    thumbUrl: [
        {
            required: true,
            message: "链接封面不能为空",
            trigger: "change",
        },
    ],
});

/* ----------------------------上传-start---------------------------- */
const avatarUploadRef = ref();
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
    if (!["image/png", "image/jpeg", "image/gif"].includes(rawFile.type)) {
        ElMessage.error("请上传图片格式");
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("图片大小不能超过2M!");
        return false;
    }
    return true;
};
// 上传改变
const onHttpRequest = async (uploadFile) => {
    const { file } = uploadFile
    try {
        const res: any = await uploadFile2(file);
        form.fileInfo = res
        form.fileCode = res.code
        form.thumbUrl = res.url
    } catch (e) {
        ElMessage.error(e?.message || e)
        avatarUploadRef.value.clearFiles();
    }
};

/* ----------------------------上传-end---------------------------- */
const handleClose = async () => {
    // 删除form的所有属性
    for (const key in form) {
        Reflect.deleteProperty(form, key)
        form[key] = defaultForm[key]
    }
    formRef.value.clearValidate()
}
const handleSubmit = () => {
    formRef.value.validate(async (valid: any) => {
        if (valid) {
            emit('update:modelValue', false)
            emit("submit", {...form});
        }
    });
};

watch(
    () => form.thumbUrl,
    () => {
        formRef.value.clearValidate(['thumbUrl']);
    }
);
</script>
<style lang="scss" scoped>
.el-form.form_link {
    margin: 10px;

    .el-form-item {
        margin-bottom: 18px !important;
    }
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader {
    :deep(.el-upload) {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);

        &:hover {
            border-color: var(--el-color-primary);
        }
    }
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.upload-tip {
    margin-top: 12px;
    font-size: 12px;
    color: #8c939d;
}
</style>
